package com.ccb.hfms.builder.controller;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.ccb.hfms.builder.service.IMongoCRUD;

@RestController
@RequestMapping("/form")
public class FormController {
	
	Logger logger = LoggerFactory.getLogger(FormController.class);

    @Autowired
    private MongoTemplate mongoTemplate;
    
    @Autowired
    private IMongoCRUD crud;
    
    @RequestMapping(value="/save",method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public JSONObject save(@RequestBody JSONObject json) {    	
    	logger.debug(json.toJSONString());
    	if(!json.containsKey("id")) {
    		throw new RuntimeException("json must contains id!");
    	}
    	Query query =new Query(Criteria.where("id").is(json.getString("id")));
    	List ret = mongoTemplate.find(query, JSONObject.class);
    	if(ret!=null && ret.size()>0) {
    		return mongoTemplate.findAndReplace(query, json);
    	}else {
    		return mongoTemplate.save(json);
    	}
    	
    }
    
   
    
    
    @RequestMapping("/queryAllForm")
    public List<JSONObject> query() {
    	Query query =new Query();
    	List<JSONObject> ret = mongoTemplate.find(query, JSONObject.class);
    	return ret;
    }
    
    @RequestMapping("/removeAllForm")
    public void removeAll() {
    	crud.remove("display", "form");
    }
    
    
    
}
